import { DataSource } from 'typeorm';
import { File } from '../../../entities/file.entity';
import { Task } from '../../../entities/task.entity';
import { User } from '../../../entities/user.entity';
import { join } from 'path';
import * as fs from 'fs';
import { v4 as uuidv4 } from 'uuid';

/**
 * 文件种子数据
 * 负责初始化示例文件数据
 */
export class FileSeed {
  constructor(private dataSource: DataSource) {}

  public async run(): Promise<void> {
    console.log('初始化文件数据...');

    const fileRepository = this.dataSource.getRepository(File);
    const taskRepository = this.dataSource.getRepository(Task);
    const userRepository = this.dataSource.getRepository(User);

    // 检查是否已存在文件数据
    const existingFiles = await fileRepository.count();
    if (existingFiles > 0) {
      console.log('文件数据已存在，跳过初始化');
      return;
    }

    try {
      // 查找管理员用户
      const admin = await userRepository.findOne({ where: { username: 'admin' } });
      if (!admin) {
        throw new Error('未找到管理员用户，无法初始化文件数据');
      }

      // 查找普通用户
      const user = await userRepository.findOne({ where: { username: 'user' } });
      if (!user) {
        throw new Error('未找到普通用户，无法初始化文件数据');
      }

      // 获取三个最新的任务用于关联文件
      const tasks = await taskRepository.find({
        order: { createdAt: 'DESC' },
        take: 3,
      });

      if (tasks.length === 0) {
        throw new Error('未找到任务数据，无法初始化文件数据');
      }

      // 确保上传目录存在
      const uploadPath = join(process.cwd(), 'uploads');
      if (!fs.existsSync(uploadPath)) {
        fs.mkdirSync(uploadPath, { recursive: true });
      }

      // 创建示例文件信息
      const fileData = [
        {
          originalName: '项目需求文档.docx',
          filename: `${uuidv4()}.docx`,
          path: `uploads/${uuidv4()}.docx`,
          mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          size: 15240,
          description: '包含项目全部需求的详细文档',
          uploaderId: admin.id,
          taskId: tasks[0].id,
        },
        {
          originalName: '设计草图.png',
          filename: `${uuidv4()}.png`,
          path: `uploads/${uuidv4()}.png`,
          mimeType: 'image/png',
          size: 256000,
          description: '项目界面设计草图',
          uploaderId: user.id,
          taskId: tasks[1].id,
        },
        {
          originalName: '进度报告.pdf',
          filename: `${uuidv4()}.pdf`,
          path: `uploads/${uuidv4()}.pdf`,
          mimeType: 'application/pdf',
          size: 512000,
          description: '项目开发阶段性进度报告',
          uploaderId: admin.id,
          taskId: tasks[2].id,
        },
      ];

      // 在文件系统中创建空文件（作为示例）
      for (const file of fileData) {
        const filePath = join(process.cwd(), file.path);
        fs.writeFileSync(filePath, ''); // 创建空文件
      }

      // 保存到数据库
      for (const file of fileData) {
        await fileRepository.save(fileRepository.create(file));
        console.log(`添加文件: ${file.originalName}`);
      }

      console.log('文件数据初始化完成');
    } catch (error) {
      console.error('初始化文件数据时出错:', error);
      throw error;
    }
  }
}